//
//  SingleViewController.m
//  Feel_at_home
//
//  Created by dlios on 15/9/23.
//  Copyright © 2015年 Feel_at_home. All rights reserved.
//

#import "SingleViewController.h"
#import <AFNetworking.h>
#import <UIImageView+WebCache.h>
#import "SingleDetilsViewController.h"
#import "SingleModel.h"
#import "Singlecolltiongviecell.h"
#import <MJRefresh.h>
#import "SingleSearchViewController.h"
#import "MusicViewController.h"
#import <MBProgressHUD.h>
#import "WidthAndHeight.pch"
#import "HTTPTOOL.h"

#define w self.view.frame.size.width
#define h self.view.frame.size.height

@interface SingleViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UIScrollViewDelegate,UISearchBarDelegate>
@property (nonatomic ,strong) UICollectionView *collectionView;
@property (nonatomic ,strong) NSMutableArray *arr;
@property (nonatomic ,strong) NSMutableDictionary *dic;
@property (nonatomic ,assign) NSInteger number;
@property (nonatomic ,assign) BOOL white;
@property (nonatomic ,strong) UISearchBar *searchBar;
@property (nonatomic ,strong) UIButton *musicButton;
@property (nonatomic ,strong) MBProgressHUD *HUD;

@property (nonatomic, retain) NSString *singlePath;

@end

@implementation SingleViewController

- (void)viewWillAppear:(BOOL)animated
{
    self.searchBar.alpha = 1;
    self.musicButton.alpha = 1;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.translucent = YES;

//    self.navigationItem.title = @"单品";

    /* 获取要保存的路径(哪一个文件夹),文件保存到Caches 文件中 */
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    /* 2. 创建文件路径
     * 数组存入本地,若文件名没有后缀,默认市XML 格式
     */
    self.singlePath = [cachePath stringByAppendingPathComponent:@"single.plist"];
    NSLog(@"879897 == %@",self.singlePath);
#pragma mark - //回首键盘
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyBoardjide:)];
    tap.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tap];

    
    [self dataHandle];
    
    
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(70*w/375, 5*h/667 , 250*w/375, 40*h/667)];
    self.searchBar.searchBarStyle = 0;
    self.searchBar.placeholder = @"家居,日用品...";
    [self.navigationController.navigationBar addSubview:self.searchBar];
    self.searchBar.delegate = self;
    
//    self.musicButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    [self.musicButton setImage:[UIImage imageNamed:@"iconfont-15"] forState:UIControlStateNormal];
    
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-15"] style:UIBarButtonItemStyleDone target:self action:@selector(musicButtonClick:)];
    
    /* UICollectionViewLayout 布局累
     作用 ： 对cell进行布局（大小，位置 等信息）
     是布局的基类 ，通常使用其子类UICollectionViewFlowLayout创建对象
     */
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    /* 更改item 大小 默认（50 * 50） */
    flowLayout.itemSize = CGSizeMake(w / 2-20, w / 2 -20);
    
    /* 设置item 上下之间的距离（最小值）*/
    flowLayout.minimumLineSpacing = 10;
    
    /* 设置item 左右之间的距离（最小值） */
    flowLayout.minimumInteritemSpacing = 10;
    
    /* 设置距四边地距离 */
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    
    /* 创建对象 */
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) collectionViewLayout:flowLayout];
    /* 背景颜色默认是黑色 */
    
    /* 两个协议 */
    self.collectionView.delegate = self;
    self.collectionView.dataSource =self;
    [self.view addSubview:self.collectionView];
    
    self.collectionView.backgroundColor = [UIColor colorWithRed:0.957 green:1.000 blue:0.961 alpha:1.000];
    
    //    [self.collectionView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:@"aaa"];
    
    
    
    [self.collectionView registerClass:[Singlecolltiongviecell class] forCellWithReuseIdentifier:@"reuse"];
    self.arr = [[NSMutableArray alloc]init];
    
    self.collectionView.header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
        [self.collectionView.header beginRefreshing];
        self.number = 0;
        [self dataHandle];
    }];
    
    
    self.collectionView.footer = [MJRefreshAutoGifFooter footerWithRefreshingBlock:^{
        [self.collectionView.footer beginRefreshing];
        self.number +=20;
        
        [self dataHandle];
    }];
    
        self.HUD = [[MBProgressHUD alloc] initWithFrame:CGRectMake(0, 0, w , h )];
        self.HUD.backgroundColor = [UIColor whiteColor];
        self.HUD.labelText = @"加载中...";
        self.HUD.labelFont = [UIFont systemFontOfSize:13];
        self.HUD.mode = 0;
        self.HUD.labelColor = [UIColor colorWithRed:1.000 green:0.647 blue:0.934 alpha:1.000];
        [self.view addSubview:self.HUD];
        [self.HUD show:YES];


    
}

- (void)musicButtonClick:(UIButton *)button
{
    MusicViewController *music = [[MusicViewController alloc] init];
    [self.navigationController pushViewController:music animated:YES];
//    [self presentViewController:music animated:YES completion:^{
//        
//    }];
//    self.musicButton.alpha = 0;
    
}



- (void)keyBoardjide:(UITapGestureRecognizer *)tap
{
        [self.searchBar resignFirstResponder];
}


//- (void)scrollViewDidScroll:(UIScrollView *)scrollView
//{
//    if (scrollView == self.collectionView) {
//        if (scrollView.contentOffset.y >= 10) {
//            self.navigationController.navigationBar.frame = CGRectMake(0, -scrollView.contentOffset.y, self.view.frame.size.width, 64);
//        }
//    }
//}


- (void)dataHandle
{
    NSString *url = [NSString stringWithFormat:@SingleViewUrl, self.number];
 
      [HTTPTOOL GETWithURL:url body:nil httpHead:nil responseStyle:JSON success:^(id result) {
        
          /* 3. 写入缓存文件 */
          [result writeToFile:self.singlePath atomically:YES];
        
       NSMutableArray *array = [[result objectForKey:@"data"] objectForKey:@"items"];
        
        for (NSDictionary *dic in array) {
            NSDictionary *datadic = [dic objectForKey:@"data"];
            SingleModel *model = [[SingleModel alloc]init];
            [model setValuesForKeysWithDictionary:datadic];
            [self.arr addObject:model];
            
        }
        
        [self.collectionView reloadData];
        [self.collectionView.header endRefreshing];
        [self.collectionView.footer endRefreshing];
        [self.HUD hide:YES];
        
    } fail:^(NSError *error) {
        
         NSDictionary *dic1 = [NSDictionary dictionaryWithContentsOfFile:self.singlePath];
        
         NSMutableArray *array = [[dic1 objectForKey:@"data"] objectForKey:@"items"];
        
        for (NSDictionary *dic in array) {
            NSDictionary *datadic = [dic objectForKey:@"data"];
            SingleModel *model = [[SingleModel alloc]init];
            [model setValuesForKeysWithDictionary:datadic];
            [self.arr addObject:model];
            
        }

        [self.collectionView reloadData];
        [self.collectionView.header endRefreshing];
        [self.collectionView.footer endRefreshing];
        [self.HUD hide:YES];
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请检查您的网络" preferredStyle:UIAlertControllerStyleAlert];
        /* 添加 action */
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            
        }];
        [alert addAction:action1];
        /* VC模态推出 alert 界面 */
        [self presentViewController:alert animated:YES completion:^{
            
           [self.HUD hide:YES];
        }];

        
    }];
    
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.arr.count;
    
    
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    Singlecolltiongviecell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    SingleModel *model = [self.arr objectAtIndex:indexPath.row];
    cell.name.text = model.name;
    cell.price.text = [NSString stringWithFormat:@"%@￥",model.price];
    [cell.imageview sd_setImageWithURL:[NSURL URLWithString:model.cover_image_url]];
    
    
    
    return cell;
    
}



- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    SingleDetilsViewController *secon = [[SingleDetilsViewController alloc] init];
    [self.navigationController pushViewController:secon animated:YES];
    SingleModel *model = [self.arr objectAtIndex:indexPath.row];
//    secon.myid = model.id;
    NSLog(@"########%@",model.id);
    secon.myid =  model.url;
    
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    SingleSearchViewController *searchbar = [[SingleSearchViewController alloc] init];
    [self.navigationController pushViewController:searchbar animated:YES];
    searchbar.search = self.searchBar.text;
    [self.searchBar resignFirstResponder];
    self.searchBar.alpha = 0;

    
//    NSLog(@"$$$$$$$$$%@",searchbar.myId);
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
